package com.cictec.middleware.gps.engine.event.listener;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.core.entity.Bus;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.BusInstanceEngine;
import com.cictec.middleware.gps.engine.TimeEventBus;
import com.cictec.middleware.gps.engine.event.BusLineChangeEvent;
import com.cictec.middleware.gps.engine.send.SendHandler;
import com.cictec.middleware.gps.service.BusService;
import com.google.common.eventbus.Subscribe;

/**
 * 设备上下线 事件处理监听【中间件外部事件】
 * 
 * @author Administrator
 *
 */
@Component
public class BusLineChangeEventListener {

	private static Logger logger = LoggerFactory.getLogger(BusLineChangeEventListener.class);

	@Autowired
	private TimeEventBus timeEventBus;

	@Autowired
	private BusInstanceEngine busInstanceEngine;
	@Autowired
	private BusService busService;

	@PostConstruct
	public void init() {
		logger.debug("注册【BusLineChangeEventListener】到TimeEventBus， 监听器：BusLineChangeEventListener ---> 事件：BusLineChangeEvent");
		timeEventBus.register(this);

	}

	/**
	 * 更新车辆所在线路
	 * 
	 * @param event
	 */
	@Subscribe
	public void onHandler(BusLineChangeEvent event) {
		logger.debug(" 设备在线、离线状态 发生变化，更新数据库；重新发布车辆位置信息");

		BusInstance busInstance = busInstanceEngine.getBusInstanceByBusUuid(event.getBusUuid());

		Bus bus = busInstance.getBus();
		bus.setBusWorkingLineUuid(event.getNewLineUuid());

		busService.updateBusWorkingLine(bus);
		
		if(!PMSUtils.isEmpty(event.getOldLineUuid())){
			SendHandler.sendBusChangeLineToStomp(event.getBusUuid(), event.getOldLineUuid(), event.getNewLineUuid());
		}
		
	}

}
